from django import template

from popboard.helpers import is_user_moderator

register = template.Library()

class IfModeratorNode(template.Node):
    def __init__(self, user, category, nodelist_true, nodelist_false):
        self.user = template.Variable(user)
        self.category = template.Variable(category)
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false

    def render(self, context):
        try:
            user = self.user.resolve(context)
            category = self.category.resolve(context)
        except template.VariableDoesNotExist:
            return self.nodelist_false.render(context)
        
        if is_user_moderator(user, category):
            return self.nodelist_true.render(context)
        return self.nodelist_false.render(context)


def do_ifmoderator(parser, token):
    """
    Renders node according to if user is the moderator of a forum or not
    Example::
        {% ifmoderator user category %}
            <p>Moderator Functions</p>
        {% else %}
            <p>No Soup for you!</p>
        {% endifmoderator %}
    """
    bits = token.contents.split()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes exactly two arguments" % bits[0])
    nodelist_true = parser.parse(('else', 'endifmoderator'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifmoderator',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfModeratorNode(bits[1], bits[2], nodelist_true, nodelist_false)

register.tag('ifmoderator', do_ifmoderator)